package com.httputils;

import java.io.File;
import java.io.InputStream;
import java.security.MessageDigest;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.os.Parcelable;
import android.os.StatFs;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;

/**
 *  功能：常用问题解决工具类
 * @author User
 *
 */
public class MyUtils {

	public static Context mCon;

	/**
	 * 递归将视图布局里面的界面VIEW回收
	 * 
	 * @param root
	 */
	public static void recycle(ViewGroup root) {
		int childCount = root.getChildCount();
		for (int i = 0; i < childCount; ++i) {
			View v = root.getChildAt(i);
			if (v instanceof ViewGroup) {
				recycle((ViewGroup) v);
			} else {
				v = null;
			}
		}
	}

	/**
	 * 以最省内存的方式读取本地资源的图片
	 * 
	 * @param context
	 * @param resId
	 * @return
	 */
	public static Bitmap readBitMap(Context context, int resId) {
		BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inPreferredConfig = Bitmap.Config.RGB_565;
		opt.inPurgeable = true;
		opt.inInputShareable = true;
		// 获取资源图片
		InputStream is = context.getResources().openRawResource(resId);
		return BitmapFactory.decodeStream(is, null, opt);
	}

	/*** 关闭虚拟键盘 */
	public static void closeInputMethodWindow(Context context, View view) {
		InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
		if (imm != null && view != null) {
//			view.setFocusable(false);// 若设成true，键盘收了，但是出现焦点问题会导致键盘事件无法传递
//			view.setFocusableInTouchMode(false);
//			view.requestFocus();
			imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
		}
	}

	/**
	 * 获取应用版本号
	 * 
	 * @param context
	 * @return
	 */
	public static String getVersionName(Context context) {
		String versionName = "1.0";
		try {
			PackageInfo mPackageInfo = context.getPackageManager()
					.getPackageInfo(context.getPackageName(), 0);
			versionName = mPackageInfo.versionName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return versionName;
	}

	/**
	 * 能进入此方法的前提是sd卡已经加载 注：调用前需判断SD卡是否存在
	 * 
	 * @return sd卡剩余空间
	 */
	public static long getSdRemainRoom() {
		File path = Environment.getExternalStorageDirectory();
		StatFs stat = new StatFs(path.getPath());
		long blockSize = stat.getBlockSize();
		long availableBlocks = stat.getAvailableBlocks();
		return availableBlocks * blockSize;

	}

	/**
	 * 为网络请求加载共有的参数
	 * 
	 * @param paramList 请求参数集合
	 * @param
	 * @param lon 经度
	 * @param lat 纬度
	 * @param city 城市
	 * @param
	 */
	public static void setPublicRequest(List<NameValuePair> paramList, String lon, String lat, String city) {
		paramList.add(new BasicNameValuePair("imei", TransactionValues.DEVICEIMEI));
		paramList.add(new BasicNameValuePair("lon", lon));
		paramList.add(new BasicNameValuePair("lat", lat));
		paramList.add(new BasicNameValuePair("city", city));
		paramList.add(new BasicNameValuePair("deviceToken", ""));
		paramList.add(new BasicNameValuePair("attest", ""));// 看签名要不要加
	}

	public static void getDeviceInfo(Context con) {
		TelephonyManager tm = (TelephonyManager) con.getSystemService(Context.TELEPHONY_SERVICE);
		if (tm.getDeviceId() != null) {
			TransactionValues.DEVICEIMEI = tm.getDeviceId();
		} else {// 获取不到IMEI时获取MAC标识唯一
			WifiManager wifiManager = (WifiManager) con.getSystemService(Context.WIFI_SERVICE);
			TransactionValues.DEVICEIMEI = wifiManager.getConnectionInfo().getMacAddress();
		}
	}

	/**
	 * 创建桌面快捷方式
	 * 
	 * @param con
	 */
	public static void checkShortCut(final Context con) {
		SharedPreferences shortCutSp = con.getSharedPreferences("isAddShortCut", Context.MODE_PRIVATE);
		boolean isFirst = shortCutSp.getBoolean("isFirst", true);
		if (isFirst) {
			Builder dialog = new Builder(con);
			dialog.setTitle("提示");
			dialog.setMessage("是否要在桌面创建快捷方式？");
			dialog.setPositiveButton("确定", new OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
					Intent shortcutIntent = con.getPackageManager().getLaunchIntentForPackage(
							con.getPackageName());
					shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); // 添加快捷方式的启动intent
					try {
						PackageManager pm = con.getPackageManager();
						String title = pm.getApplicationLabel(
								pm.getApplicationInfo(con.getPackageName(), PackageManager.GET_META_DATA))
								.toString();// 获取当前应用名称
						int iconId = pm.getApplicationInfo(con.getPackageName(),
								PackageManager.GET_UNINSTALLED_PACKAGES).icon;
						Parcelable iconResource = Intent.ShortcutIconResource.fromContext(con, iconId);
						shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);// 快捷方式的图标
						shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, title); // 快捷方式名称
						shortcut.putExtra("duplicate", false); // 不允许重复创建（不一定有效）
					} catch (NameNotFoundException e) {
						e.printStackTrace();
					}
					con.sendBroadcast(shortcut);
				}
			}).setNegativeButton("取消", null).show();
			shortCutSp.edit().putBoolean("isFirst", false).commit();
		}
	}

	/**
	 * 生成签名并保存到交易常量中
	 */
	public static void generateSignature(Context con) {
		// 获得程序的签名并hash一下
		String[] temp = PackageUtil.getCertMsg(con.getPackageName(), con);
		int signature = HashAlgorithms.FNVHash1(temp[0].substring(0, 4) + temp[0].substring(6, 8));
		if (2 == NetworkConstant.COMM_TYPE) {

			TransactionValues.SIGNATURE = String.valueOf(signature);// 投产时打开该注释
		} else {
		}
	}

	/**
	 * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
	 */
	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	/**
	 * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
	 */
	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	/**
	 * MD5加密
	 * 
	 * @param s
	 * @return
	 */
	public final static String MD5(String s) {
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
		try {
			byte[] btInput = s.getBytes();
			// 获得MD5摘要算法的 MessageDigest 对象
			MessageDigest mdInst = MessageDigest.getInstance("MD5");
			// 使用指定的字节更新摘要
			mdInst.update(btInput);
			// 获得密文
			byte[] md = mdInst.digest();
			// 把密文转换成十六进制的字符串形式
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 关闭软键盘
	 * 
	 * @param activity
	 */
	public static void closeKeyboard(Activity activity) {
		View view = activity.getWindow().peekDecorView();
		if (view != null) {
			InputMethodManager inputmanger = (InputMethodManager) activity
					.getSystemService(Context.INPUT_METHOD_SERVICE);
			inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
		}
	}

	/**
	 * 验证字符串是否包含数字
	 * 
	 * @param content 要验证的字符串
	 * @return
	 */
	public static boolean hasDigit(String content) {
		boolean flag = false;
		Pattern p = Pattern.compile(".*\\d+.*");
		Matcher m = p.matcher(content);
		if (m.matches())
			flag = true;
		return flag;
	}

	/**
	 * 判断是否登录超时
	 * 
	 * @param str 被验证信息
	 * @return
	 */
	public static boolean loginTimeOut(String str) {
		if ("98".equals(str)) {
			return true;
		}
		return false;
	}

}
